import lib from '../jsm/ThreeLib.js'
import { Color } from 'https://unpkg.com/three/build/three.module.js';

const defAttr = () => ({
    gl: null,
    vertices: [],
    geoData: [],
    size: 2,
    attrName: 'a_Position',
    count: 0,
    pointSize: 20,
    types: [
        "POINTS",
        "TRIANGLES", "TRIANGLE_STRIP", "TRIANGLE_FAN",
        "LINES", "LINE_STRIP", "LINE_LOOP",
    ],
    Color: [1, 1, 1, 1]
})

export default class Poly {
    constructor(attr) {
        Object.assign(this, defAttr(), attr);
        this.init();
    }
    init() {
        const { count, size, gl, pointSize } = this;
        if (!gl) { return; }

        gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());

        const a_Position = gl.getAttribLocation(gl.program, 'a_Position');
        gl.vertexAttribPointer(this.attrName, size, gl.FLOAT, false, 0, 0);

        var a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');
        gl.vertexAttrib1f(a_PointSize, pointSize);

        if (!!this.Color) {
            var u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
            gl.uniform4fv(u_FragColor, this.Color);
        }


        gl.enableVertexAttribArray(a_Position);

        this.updateBuffer();

    }
    updateBuffer() {
        const { gl, vertices } = this;
        this.updateCount();
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
    }
    updateCount() {
        this.count = this.vertices.length / this.size;
    }
    addVertice(...params) {
        this.vertices.push(...params);
        this.updateBuffer();
    }
    popVertice() {
        const { vertices, size } = this;
        const len = vertices.length;
        vertices.splice(len - size, len);
        this.updateCount();
    }
    setVertice(index, vertexX, vertexY) {
        const { vertices, size } = this;
        vertices[index * size - 2] = vertexX;
        vertices[index * size - 1] = vertexY;
        this.updateBuffer();
    }
    updateVertices(params) {
        const { geoData } = this;
        const vertices = [];
        geoData.forEach(data => {
            params.forEach(key => {
                vertices.push(data[key])
            })
        })
        this.vertices = vertices;
    }
    draw(types = this.types) {
        const { gl, count } = this;
        lib.clearCanvas(gl, new Color("rgba(0,0,0,1)"), 1);
        for (let type of types) {
            gl.drawArrays(gl[type], 0, count);
        }

    }
}